package com.openspring.platform.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.openspring.framework.tree.Node;
import com.openspring.framework.util.ResultUtils;
import com.openspring.platform.service.SecurityService;

@Controller
@RequestMapping("security")
public class SecurityController {

	private SecurityService securityService;

	@Resource(name="securityService")
	public void setSecurityService(SecurityService securityService) {
		this.securityService = securityService;
	}
	
	@RequestMapping(value="/findOperators/{id}", method=RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> findOperators(@PathVariable("id") Long resourceId) {
		List<Map<String, Object>> entities = securityService.findResourceOperators(resourceId);
		return ResultUtils.datas(entities);
	}
	
	@RequestMapping(value="/saveOperators", method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> saveOperators(@RequestParam("id") Long resourceId, @RequestParam(value="ids", required=false) Long...operatorId) {
		securityService.saveResourceOperators(resourceId, operatorId);
		return ResultUtils.success();
	}
	
	@RequestMapping(value="/getoperatorpermissionstree/{id}", method=RequestMethod.GET)
	@ResponseBody
	public Node getOperatorPermissionsTree(@PathVariable("id") Long roleId) {
		return securityService.getOperatorPermissionsTree(roleId);
	}
	
	@RequestMapping(value="/saveoperatorpermissions", method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> saveOperatorPermissions(@RequestParam("id") Long roleId, 
			@RequestParam(value="rIds", required=false) Long[] resourceIds, 
			@RequestParam(value="oIds", required=false) Long[] operatorIds) {
		securityService.saveOperatorPermissions(roleId, resourceIds, operatorIds);
		return ResultUtils.success();
	}
	
	/**
	 * select * , 
CASE WHEN
(select distinct(operatorId) from t_platform_permission_role t3 
where t3.roleId in(
	select t1.roleId from t_platform_user_role t1 
	left join t_platform_role t2 on t1.roleId = t2.id 
	where t1.userId = 2 and t2.status = 1) 
and t3.resourceId = t5.resourceId and t3.operatorId = t4.id) 
IS NULL then true else false end as disabled
from t_platform_operator t4
left join t_platform_permission t5
on t5.operatorId = t4.id
where t4.status = 1 AND t5.resourceId = 9
	 */
}